﻿<%@ WebHandler Language="C#" Class="ZSExchangeInfoCreateHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
/// <summary>
/// 串件单创建
/// </summary>
public class ZSExchangeInfoCreateHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSExchangeBillIbusiness m_ExchangeBill = uMESBusinessFactory.instance.GetuLMSExchangeBillObject();
    private uLMSCommonIBusiness m_CommonBusiness = uMESBusinessFactory.instance.GetuLMSCommonObject();
    CollectERPConfirmBusines r_Mconfirm = new CollectERPConfirmBusines();
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "InitData"://查询订单信息
                    InitData(context);
                    break;
                case"GetBigSmallData":
                    getBigSmallData(context);
                    break;    
                case"getEngineNoByFactoryID":
                    getEngineNoByFactoryID(context);
                    break;    
                case"SaveExchangeData":
                    SaveExchangeData(context);
                    break;    
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

    private void InitData(HttpContext context) 
    {
        var result = new uMESProcessResult();
        var ExchangeID = context.Request["ExchangeID"].ToString();
        var para=new Dictionary<string,string>();
        para.Add("ExchangeID", ExchangeID);
        DataTable st = m_ExchangeBill.SearchExchangeBill(para);
        result.Result = st.Rows.Count > 0;
        result.ReturnData = st;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private void getBigSmallData(HttpContext context) 
    {
        var result = new uMESProcessResult();
        //var PopupData = (Dictionary<string, Object>)context.Session["PopupData"];
        var PopupData = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var name = context.Request["name"].ToString();
        var strsql = @"SELECT DISTINCT p2.productname,cm.productbatchno, p.description productdesc,p.productid
                     	FROM CONTAINERCURRENTINFO c 
                     	LEFT JOIN PRODUCTMATERIALLISTITEM p1 ON p1.BOMID =c.BOMID 
                     	LEFT JOIN issueerpmaterial im ON im.CONTAINERID =c.CONTAINERID 
                     	LEFT JOIN Collecterpmaterial cm ON im.collecterpmaterialid=cm.collecterpmaterialid 
                     	LEFT JOIN product p ON p.productid=p1.productid
                     	LEFT JOIN PRODUCTBASE p2 ON p2.PRODUCTBASEID =p.PRODUCTBASEID 
                     	WHERE c.CONTAINERID ='{0}' {1} ORDER BY p2.productname";
        var strsql2 = @"SELECT DISTINCT cm.productname,cm.productbatchno, p.description productdesc,pm.productid  
                        FROM issueerpmaterial im     
                         LEFT JOIN Collecterpmaterial cm ON im.collecterpmaterialid=cm.collecterpmaterialid     
 						LEFT JOIN partmenuinfo pm ON im.partmenuinfoid=pm.partmenuinfoid 
                     	LEFT JOIN product p ON pm.productid=p.productid
                     	WHERE im.ContainerNo='{0}' {1} ORDER BY cm.productname";
        var strname=string.Empty;
        if (!string.IsNullOrWhiteSpace(name)) { strname = " and (p2.productname like '%" + name + "%' or  p.description like '%" + name + "%')"; }
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(string.Format(strsql, PopupData["CId"].ToString(), strname));
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 
    /// </summary>
    private void getEngineNoByFactoryID(HttpContext context) 
    {
        var result = new uMESProcessResult();
        var name = context.Request["name"].ToString();
        var strsql = @"SELECT DISTINCT u.ATTRIBUTEVALUE PRODUCTNAME,u.ATTRIBUTEVALUE PRODUCTID FROM MFGORDER m 
                inner JOIN USERATTRIBUTE u ON u.PARENTID =m.MFGORDERID AND u.USERATTRIBUTENAME ='发动机'
                WHERE  m.FACTORYID ='" +m_UserInfo.FactoryID+"'";
        if (!string.IsNullOrWhiteSpace(name)) { strsql+= " and u.ATTRIBUTEVALUE like '%" + name + "%' "; }
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(strsql);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    
    /// <summary>
    /// 获取串件单--顺序号--
    /// </summary>
    /// <returns></returns>
    private string GetNextFlowSN()
    {
        var strPrefix = m_UserInfo.FactoryCode + "-C" + DateTime.Now.Year.ToString() + "-";
        var ExchangeName = strPrefix + m_ExchangeBill.GetNextFlowSN(strPrefix);
        return ExchangeName;
    }

    private void SaveExchangeData(HttpContext context) 
    {
        var result = new uMESProcessResult();
        //var argDt = JsonConvert.DeserializeObject<DataTable>(context.Request["data"].ToString());
        var paraDt = JsonConvert.DeserializeObject<Dictionary<string,string>>(context.Request["data"].ToString());
        var PopupData = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["para"].ToString());
        
        var dto = new ExchangeBillInfoDTO();
        dto.BillProperty = "单串";//串件性质
        dto.ContainerName = "";//批次号
        dto.ContainerID = PopupData["CId"].ToString();//批次ID
        dto.ComContainerName ="";//组合零件号
        dto.ExchangeID = string.IsNullOrWhiteSpace(PopupData["ExchangeID"].ToString()) ? Guid.NewGuid().ToString() : PopupData["ExchangeID"].ToString();//---------0
        dto.ExchangeName = PopupData["ExchangeName"].ToString();//单据名称唯一--------1
        dto.CreateDate = paraDt["ExchangeDate"];//创建日期--------2
        dto.ExchangeMethod = paraDt["ExchangeMethod"];//串件方式--------3、4
        dto.ExchangeCodeNo = paraDt["ExchangeCodeNo"];//(被串)新机（品）/修理机（品）编号----5
        dto.ContainerNo = paraDt["ContainerNo"];//流水卡NO任务单装试(任务号)-----------6
        dto.ProductID = paraDt["ProductID"];//零件号--7、8
        dto.ERPBatchNo = paraDt["ERPBatchNo"];//零组件批次号--9
        dto.FactoryWorkHours = paraDt["FactoryWorkHours"];//厂内工作时间----10
        dto.WorkHours = paraDt["WorkHours"];//工作时间(小时)-------11
        dto.Qty = paraDt["Qty"];//被串数量---12
        dto.Reason = paraDt["Reason"]; //原因--------13
        dto.BillSource = paraDt["Source"];//串件来源---14
        dto.UpExchangeCodeNo = paraDt["UpExchangeCodeNo"];//新机（品）/修理机（品）编号--15
        dto.UpContainerNo = paraDt["UpContainerNo"];//任务号--16
        dto.UpQty = paraDt["UpQty"];//数量--17
        dto.UpBatchNo = paraDt["UpBatchNo"];//零组件批次号--18
        dto.TotalWorkHours = paraDt["TotalWorkHours"];//累计工作时间/总寿命--19
        dto.IsOverFactoryTime = paraDt["IsOverFactoryTime"];//是否大于被串件厂内工作时间--20
        dto.ExchangeType = paraDt["ExchangeType"];//串件类型
        dto.Actual = "";//实际
        dto.Machine = PopupData["MachineName"].ToString();//上机号
        dto.MapRequest = "";//图纸要求
        dto.Note = "";//备注
        dto.EmployeeID = m_UserInfo.EmployeeID;//创建人
        dto.FactoryID =m_UserInfo.FactoryID;//分厂ID
        dto.BillType = "串件单";//串件（类型周转单,串件单）
        dto.IsTransfer = "0";//结转标记
        dto.IsUse = "0";//是否有效记录


        if (string.IsNullOrWhiteSpace(PopupData["ExchangeID"].ToString()))
        {
            if (!m_ExchangeBill.CheckExists(dto.ExchangeID, dto.ExchangeName))
            {
                result.Result=m_ExchangeBill.InsertExchangeBill(dto);
                result.Message = result.Result ? "保存成功" : "保存失败";
                result.ReturnData = result.Result ? dto.ExchangeID : string.Empty;
            }
            else { result.Message = "编号重复"; }
        }
        else { 
             var conditionPara=new Dictionary<String, String>();
                conditionPara.Add("Exchangebillid", "'" + PopupData["ExchangeID"].ToString() + "'");
                conditionPara.Add("isuse", "0");
                DataTable tempDt = m_CommonBusiness.GetTableInfoByField("EXCHANGEBILLdealinfo", conditionPara, null);
                if (tempDt.Select(" Billstatus<>5 ").Length > 0) { result.Message = "有确认记录，不能修改"; }
                else {
                    result.Result = m_ExchangeBill.UpdateExchangeBill(dto);
                    result.Message =result.Result ? "更新成功" : "更新失败";
                    result.ReturnData = result.Result ? dto.ExchangeID : string.Empty;
                }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

}